/*
 * @Descripttion: 自有3D高程信息
 * @Use: 使用
 * @Author: yeming
 * @Date: 2021-08-26 11:27:52
 */

import COOKIE from "@/common/scripts/cookie";
import $api from "@/api";
import $md5 from 'js-md5';

const URL = {
  "testForever": "http://192.168.18.235:9099/tms/terrain/wgs84/WEB_D6y3CD4L14Vqv-6641-b72d5b255915839c67a9c6f11ad9ec28", // 永久测试地址
  "test": "http://192.168.18.235:9099/tms/terrain/wgs84/",
  "online": "https://map.tusuav.com:9099/tms/terrain/wgs84/"
}

export function selfTerrainProvider (Map, token) { // Map => cesium 剖出的实例
  let auth3D = "";
  if (COOKIE.get("yxla_auth3d")) auth3D = COOKIE.get("yxla_auth3d");
  Map.map3d.scene.terrainProvider = new window.Cesium.CesiumTerrainProvider({
    // url: URL.test + auth3D
    url: URL.online + auth3D
  });
  // readyPromise 回调函数需要时间，promise只有then没有catch，暂时无法监听到err
  let flag = 0; // 3D地形图是否成功渲染
  Map.map3d.scene.terrainProvider.readyPromise.then(() => {
    flag = 1;
  });

  // yxla_auth3d失效，二次请求接口加载3D地图
  setTimeout(() => {
    if (flag) return false;

    console.log("auth3D 失效，二次请求");
    let id = "WEB_" + token;
    let data = { "id": "WEB_" + token };
    $api.Terrain.auth3D(data).then(response => {
      if (response.status >= 200 && response.status < 300) {
        let res = response.data;
        if (res.status === 1) {
          let info = res.data;
          const NEWSALT_TERRAIN = "BAY/+ZOzUOwMY"; // Terrain 3D 固定盐
          let random4 = Math.floor(Math.random() * 10000); // 4位随机数
          let _hash = $md5("mp" + info.content + random4 + NEWSALT_TERRAIN);
          auth3D = id + "-" + random4 + "-" + _hash;
          COOKIE.set("yxla_auth3d", auth3D, 4 * 60 * 60 * 1000); // 4小时后过期

          Map.map3d.scene.terrainProvider = new window.Cesium.CesiumTerrainProvider({
            url: URL.online + auth3D
          });
        }
      }
    });
  }, 3000);
};
